package com.aso114.project.exam;

import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aso114.project.R;
import com.aso114.project.adapter.ExpositionAdapter;
import com.aso114.project.adapter.PicAdapter;
import com.aso114.project.base.BaseFragment;
import com.aso114.project.bean.MsgEvent;
import com.aso114.project.bean.QuestionBaseBean;
import com.aso114.project.bean.QuestionContextListBean;
import com.aso114.project.commonview.MyListView;
import com.aso114.project.util.Helper;
import com.aso114.project.util.MySharedPreferences;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.net.URL;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by asus on 2019/1/15.
 */

public class ExpositionFragment extends BaseFragment implements ExpositionAdapter.OnItemClickListener {

    @BindView(R.id.expostion_left)
    TextView expostionLeft;
    @BindView(R.id.expostion_right)
    TextView expostionRight;
    @BindView(R.id.expostion_title)
    TextView expostionTitle;
    @BindView(R.id.expostion_min_title)
    TextView expostionMinTitle;
    @BindView(R.id.expostion_analysis)
    TextView expostionAnalysis;
    @BindView(R.id.expostion_analysis_tv)
    TextView expostionAnalysisTv;
    @BindView(R.id.expostion_left_ly)
    LinearLayout expostionLeftLy;
    @BindView(R.id.expostion_listView)
    RecyclerView expostionListView;
    @BindView(R.id.expostion_material)
    TextView expostionMaterial;
    @BindView(R.id.expostion_right_ly)
    LinearLayout expostionRightLy;
    Unbinder unbinder;
    @BindView(R.id.expostion_material_img)
    MyListView expostionMaterialImg;
    private int size = 3;
    private float minSize = 11;
    private float maxSize = 15;
    private boolean isLeft = false;

    private boolean isCollect = false;
    private QuestionBaseBean baseBean;
    private ArrayList<QuestionContextListBean> baseListBean;
    private int pageCount;
    private ExpositionAdapter adapter;
    private PicAdapter picAdapter;

    public static ExpositionFragment newInstance(int pageCount, QuestionBaseBean questionBaseBean, ArrayList<QuestionContextListBean> questionContextListBeans, boolean isCollect) {
        Bundle args = new Bundle();
        args.putInt("pageCount", pageCount);
        args.putBoolean("isCollect", isCollect);
        args.putSerializable("QuestionBaseBean", questionBaseBean);
        args.putSerializable("QuestionContextListBean", questionContextListBeans);
        ExpositionFragment fragment = new ExpositionFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected int getLayoutResourceId() {
        return R.layout.fragment_expostion;
    }

    @Override
    protected void initView() {
        baseBean = (QuestionBaseBean) getArguments().getSerializable("QuestionBaseBean");
        baseListBean = (ArrayList<QuestionContextListBean>) getArguments().getSerializable("QuestionContextListBean");
        pageCount = getArguments().getInt("pageCount");
        isCollect = getArguments().getBoolean("isCollect", false);
        expostionLeft.performClick();
        struct();
//        size = MySharedPreferences.getInstance(getActivity()).getTextSize();
//        setTitlesize(size);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(GridLayoutManager.HORIZONTAL);
        //设置布局管理器
        expostionListView.setLayoutManager(layoutManager);
        adapter = new ExpositionAdapter(getActivity(), baseListBean, 0);
        expostionListView.setAdapter(adapter);
        adapter.setOnItemClickListener(this);
        inData();
    }

    @Override
    public void onResume() {
        super.onResume();
        size = MySharedPreferences.getInstance(getActivity()).getTextSize();
        setTitlesize(size);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void setClick(MsgEvent msgEvent) {
        switch (msgEvent.getItemClick()) {
            case 1:// 小号  13  9
                minSize = 9;
                maxSize = 13;
                break;
            case 2:// 中号  14  10
                minSize = 10;
                maxSize = 14;
                break;
            case 3:// 标准  15  11
                minSize = 11;
                maxSize = 15;
                break;
            case 4:// 大号  16  12
                minSize = 12;
                maxSize = 16;
                break;
            case 5:// 巨无霸 17  13
                minSize = 13;
                maxSize = 17;
                break;
        }
        if (msgEvent.getPageCount() == pageCount) {
            expostionMinTitle.setTextSize(minSize);
            expostionTitle.setTextSize(maxSize);
            expostionAnalysisTv.setTextSize(maxSize);
            expostionMaterial.setTextSize(maxSize);
        }
    }

    private void setTitlesize(int size) {
        switch (size) {
            case 1:// 小号  13  9
                minSize = 9;
                maxSize = 13;
                break;
            case 2:// 中号  14  10
                minSize = 10;
                maxSize = 14;
                break;
            case 3:// 标准  15  11
                minSize = 11;
                maxSize = 15;
                break;
            case 4:// 大号  16  12
                minSize = 12;
                maxSize = 16;
                break;
            case 5:// 巨无霸 17  13
                minSize = 13;
                maxSize = 17;
                break;
        }
        expostionMinTitle.setTextSize(minSize);
        expostionTitle.setTextSize(maxSize);
        expostionAnalysisTv.setTextSize(maxSize);
        expostionMaterial.setTextSize(maxSize);
    }

    private void inData() {
        if (baseBean == null) {
            return;
        }
        //获取答案在第几个
        expostionTitle.setText(Html.fromHtml(baseBean.getFormatContent(), imgGetter, null));
        expostionMinTitle.setText("(" + baseBean.getRealPaperTitle() + ")");
        expostionAnalysisTv.setText("参考答案\n" + Html.fromHtml(baseBean.getQuestionsAnswerInfo().getAnswerArray().get(0).toString(), imgGetter, null));
        if (baseListBean != null && baseListBean.size() != 0) {
            expostionMaterial.setText(Html.fromHtml(baseListBean.get(0).getFormatContent(), imgGetter, null));
            if (baseListBean.get(0).getFormatImages() != null && baseListBean.get(0).getFormatImages().size() != 0) {
                // 设置图片
                expostionMaterialImg.setVisibility(View.VISIBLE);
                picAdapter = new PicAdapter(getActivity(), baseListBean.get(0).getFormatImages());
                expostionMaterialImg.setAdapter(picAdapter);
            }else {
                expostionMaterialImg.setVisibility(View.GONE);
            }
        }

    }

    Html.ImageGetter imgGetter = new Html.ImageGetter() {
        public Drawable getDrawable(String source) {
            Drawable drawable = null;
            URL url;
            try {
                url = new URL(source);
                drawable = Drawable.createFromStream(url.openStream(), ""); // 获取网路图片
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
            drawable.setBounds(0, 0, drawable.getIntrinsicWidth() + 50,
                    drawable.getIntrinsicHeight() + 50);
            return drawable;
        }
    };

    public static void struct() {
        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
                .detectDiskReads().detectDiskWrites().detectNetwork()
                .penaltyLog().build());
        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
                .detectLeakedSqlLiteObjects() // 探测SQLite数据库操作
                .penaltyLog() // 打印logcat
                .penaltyDeath().build());
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void addOnClick() {

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        EventBus.getDefault().register(this);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
        unbinder.unbind();
    }

    @OnClick({R.id.expostion_left, R.id.expostion_right, R.id.expostion_analysis})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.expostion_left:
                if (isLeft) {
                    return;
                }
                expostionLeft.setTextColor(getActivity().getResources().getColor(R.color.aff6559));
                expostionRight.setTextColor(getActivity().getResources().getColor(R.color.a333333));
                isLeft = true;
                expostionLeftLy.setVisibility(View.VISIBLE);
                expostionListView.setVisibility(View.GONE);
                expostionRightLy.setVisibility(View.GONE);
                break;
            case R.id.expostion_right:
                if (isCollect) {
                    Helper.showToast("功能正在开发中，敬请期待");
                    return;
                }
                if (!isLeft) {
                    return;
                }
                expostionLeft.setTextColor(getActivity().getResources().getColor(R.color.a333333));
                expostionRight.setTextColor(getActivity().getResources().getColor(R.color.aff6559));
                isLeft = false;
                expostionLeftLy.setVisibility(View.GONE);
                expostionListView.setVisibility(View.VISIBLE);
                expostionRightLy.setVisibility(View.VISIBLE);
                break;
            case R.id.expostion_analysis:
                expostionAnalysis.setVisibility(View.INVISIBLE);
                expostionAnalysisTv.setVisibility(View.VISIBLE);
                break;
        }
    }

    @Override
    public void onItemClick(int position) {
        expostionMaterial.setText(Html.fromHtml(baseListBean.get(position).getFormatContent()));
        adapter.notifyDataSetChanged();
        if (baseListBean.get(position).getFormatImages() != null && baseListBean.get(position).getFormatImages().size() != 0) {
            // 设置图片
            expostionMaterialImg.setVisibility(View.VISIBLE);
            picAdapter.setData(baseListBean.get(position).getFormatImages());
            picAdapter.notifyDataSetChanged();
        }else {
            expostionMaterialImg.setVisibility(View.GONE);
        }
    }
}
